using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 工具调用兼容性服务
    /// 为原生不支持函数调用的模型提供文本解析式的工具调用支持
    /// </summary>
    public class ToolCallCompatibilityService
    {
        private readonly ILogger<ToolCallCompatibilityService> _logger;
        private readonly AgentToolService _agentToolService;
        private readonly ProjectService _projectService;

        // 工具调用模式匹配
        private readonly Dictionary<string, Regex> _toolPatterns = new()
        {
            // 基础工具
            ["scan_project_structure"] = new Regex(@"scan_project_structure\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["get_project_overview"] = new Regex(@"get_project_overview\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["deep_content_search"] = new Regex(@"deep_content_search\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["analyze_story"] = new Regex(@"analyze_story\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["get_file_summary"] = new Regex(@"get_file_summary\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["analyze_file_relationships"] = new Regex(@"analyze_file_relationships\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["extract_key_information"] = new Regex(@"extract_key_information\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["get_content_statistics"] = new Regex(@"get_content_statistics\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),

            // 增强文件访问工具 / 代码智能
            ["get_path_info"] = new Regex(@"get_path_info\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["get_file_content"] = new Regex(@"get_file_content\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["batch_file_info"] = new Regex(@"batch_file_info\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["search_paths"] = new Regex(@"search_paths\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["smart_file_access"] = new Regex(@"smart_file_access\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["analyze_directory_structure"] = new Regex(@"analyze_directory_structure\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["code_search"] = new Regex(@"code_search\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["open_file_range"] = new Regex(@"open_file_range\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            // Roslyn 工具
            ["get_diagnostics"] = new Regex(@"get_diagnostics\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["find_references"] = new Regex(@"find_references\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["rename_symbol_preview"] = new Regex(@"rename_symbol_preview\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["rename_symbol_apply"] = new Regex(@"rename_symbol_apply\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["create_patch"] = new Regex(@"create_patch\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
            ["apply_patch_base64"] = new Regex(@"apply_patch_base64\s*\(\s*([^)]*)\s*\)", RegexOptions.IgnoreCase),
        };

        public ToolCallCompatibilityService(
            ILogger<ToolCallCompatibilityService> logger,
            AgentToolService agentToolService,
            ProjectService projectService)
        {
            _logger = logger;
            _agentToolService = agentToolService;
            _projectService = projectService;
        }

        /// <summary>
        /// 解析并执行文本中的工具调用
        /// </summary>
        /// <param name="text">包含工具调用的文本</param>
        /// <param name="currentProjectPath">当前项目路径</param>
        /// <returns>处理后的文本，工具调用结果会替换原始调用</returns>
        public async Task<string> ProcessToolCallsAsync(string text, string currentProjectPath = null)
        {
            if (string.IsNullOrEmpty(text))
                return text;

            var result = text;
            var processedCalls = new List<string>();

            try
            {
                // 设置当前工作目录
                if (!string.IsNullOrEmpty(currentProjectPath))
                {
                    _agentToolService.SetWorkingDirectory(currentProjectPath);
                }

                // 检测并处理每种工具调用
                foreach (var toolPattern in _toolPatterns)
                {
                    var matches = toolPattern.Value.Matches(result);
                    foreach (Match match in matches)
                    {
                        if (processedCalls.Contains(match.Value))
                            continue;

                        var toolName = toolPattern.Key;
                        var parameters = match.Groups[1].Value.Trim();

                        _logger.LogInformation($"检测到工具调用: {toolName}({parameters})");

                        try
                        {
                            var toolResult = await _agentToolService.ExecuteToolAsync(toolName, parameters);

                            // 格式化工具结果
                            var formattedResult = FormatToolResult(toolName, toolResult);

                            // 替换原始调用
                            result = result.Replace(match.Value, formattedResult);
                            processedCalls.Add(match.Value);

                            _logger.LogInformation($"工具调用成功: {toolName}");
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, $"工具调用失败: {toolName}");
                            var errorResult = $"❌ 工具调用失败: {toolName} - {ex.Message}";
                            result = result.Replace(match.Value, errorResult);
                        }
                    }
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理工具调用时发生错误");
                return $"{text}\n\n❌ 工具调用处理失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 检测文本中是否包含工具调用
        /// </summary>
        /// <param name="text">要检测的文本</param>
        /// <returns>是否包含工具调用</returns>
        public bool ContainsToolCalls(string text)
        {
            if (string.IsNullOrEmpty(text))
                return false;

            return _toolPatterns.Values.Any(pattern => pattern.IsMatch(text));
        }

        /// <summary>
        /// 获取支持的工具列表
        /// </summary>
        /// <returns>工具名称和描述的字典</returns>
        public Dictionary<string, string> GetSupportedTools()
        {
            return new Dictionary<string, string>
            {
                // 基础工具
                ["scan_project_structure"] = "扫描项目结构，获取完整目录树。用法: scan_project_structure() 或 scan_project_structure(路径)",
                ["get_project_overview"] = "生成项目整体概览和分析。用法: get_project_overview() 或 get_project_overview(路径)",
                ["deep_content_search"] = "深度搜索内容并提供上下文。用法: deep_content_search(关键词) 或 deep_content_search(关键词|路径)",
                ["analyze_story"] = "分析故事内容和结构。用法: analyze_story(文件路径)",
                ["get_file_summary"] = "生成文件内容摘要和统计信息。用法: get_file_summary(文件路径)",
                ["analyze_file_relationships"] = "分析文件间的关联关系。用法: analyze_file_relationships() 或 analyze_file_relationships(路径)",
                ["extract_key_information"] = "提取关键信息（角色/地点/事件）。用法: extract_key_information(文件路径|类型)",
                ["get_content_statistics"] = "获取详细的内容统计信息。用法: get_content_statistics() 或 get_content_statistics(路径)",

                // 增强文件访问工具 / 代码智能
                ["get_path_info"] = "获取路径详细信息（文件或目录）。用法: get_path_info(路径) 或 get_path_info(路径|包含隐藏文件|最大深度)",
                ["get_file_content"] = "智能获取文件内容。用法: get_file_content(文件路径) 或 get_file_content(文件路径|访问模式)",
                ["batch_file_info"] = "批量获取多个文件信息。用法: batch_file_info(文件路径列表) 或 batch_file_info(路径1,路径2,路径3|包含内容)",
                ["search_paths"] = "搜索匹配的文件和目录。用法: search_paths(基础路径|搜索模式) 或 search_paths(路径|模式|递归)",
                ["smart_file_access"] = "智能文件访问，自动选择最佳读取策略。用法: smart_file_access(文件路径)",
                ["analyze_directory_structure"] = "深度分析目录结构和内容分布。用法: analyze_directory_structure() 或 analyze_directory_structure(目录路径)",
                ["code_search"] = "代码搜索。用法: code_search(关键词|文件匹配模式|最大结果数)",
                ["open_file_range"] = "查看文件片段。用法: open_file_range(文件路径|起始行|结束行)",


                    // 补丁工具
                    ["create_patch"] = "生成统一diff补丁。用法: create_patch(文件路径|新内容Base64)",
                    ["apply_patch_base64"] = "应用Base64统一diff补丁到项目。用法: apply_patch_base64(Base64补丁)",

                // Roslyn 工具
                ["get_diagnostics"] = "获取项目诊断（警告/错误）。用法: get_diagnostics([项目csproj路径])",
                ["find_references"] = "查找符号引用。用法: find_references(文件|行|列)",
                ["rename_symbol_preview"] = "预览重命名符号的补丁。用法: rename_symbol_preview(文件|行|列|新名称)",
                ["rename_symbol_apply"] = "重命名并直接应用补丁。用法: rename_symbol_apply(文件|行|列|新名称)"
            };
        }

        /// <summary>
        /// 格式化工具执行结果
        /// </summary>
        /// <param name="toolName">工具名称</param>
        /// <param name="result">执行结果</param>
        /// <returns>格式化后的结果</returns>
        private string FormatToolResult(string toolName, string result)
        {
            var sb = new StringBuilder();
            sb.AppendLine($"\n🔧 **工具执行结果: {toolName}**");
            sb.AppendLine("```");
            sb.AppendLine(result);
            sb.AppendLine("```");
            sb.AppendLine();

            return sb.ToString();
        }

        /// <summary>
        /// 分析"诡异收藏家"项目
        /// </summary>
        /// <param name="projectPath">项目路径，如果为空则使用默认路径</param>
        /// <returns>项目分析结果</returns>
        public async Task<string> AnalyzeGuiYiProject(string projectPath = null)
        {
            try
            {
                // 尝试多个可能的项目路径
                var possiblePaths = new[]
                {
                    projectPath,
                    @"H:\AI创作系统\诡异收藏家",
                    @".\诡异收藏家",
                    @".\Projects\诡异收藏家",
                    @"DocumentCreationSystem\Projects\Project_3",
                    @"DocumentCreationSystem\Projects\Project_4"
                }.Where(p => !string.IsNullOrEmpty(p)).ToArray();

                string validPath = null;
                foreach (var path in possiblePaths)
                {
                    if (Directory.Exists(path))
                    {
                        validPath = path;
                        break;
                    }
                }

                if (validPath == null)
                {
                    return "❌ 未找到'诡异收藏家'项目目录。请确认项目路径是否正确。";
                }

                var result = new StringBuilder();
                result.AppendLine("# 诡异收藏家项目分析报告");
                result.AppendLine($"📍 项目路径: {validPath}");
                result.AppendLine();

                // 执行项目结构扫描
                var structureResult = await _agentToolService.ExecuteToolAsync("scan_project_structure", validPath);
                result.AppendLine("## 项目结构");
                result.AppendLine(structureResult);
                result.AppendLine();

                // 执行项目概览
                var overviewResult = await _agentToolService.ExecuteToolAsync("get_project_overview", validPath);
                result.AppendLine("## 项目概览");
                result.AppendLine(overviewResult);
                result.AppendLine();

                // 分析文件关系
                var relationshipResult = await _agentToolService.ExecuteToolAsync("analyze_file_relationships", validPath);
                result.AppendLine("## 文件关系分析");
                result.AppendLine(relationshipResult);
                result.AppendLine();

                return result.ToString();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分析诡异收藏家项目失败");
                return $"❌ 项目分析失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 生成工具使用指南
        /// </summary>
        /// <returns>工具使用指南</returns>
        public string GenerateToolGuide()
        {
            var sb = new StringBuilder();
            sb.AppendLine("# 🛠️ AI助手工具调用指南");
            sb.AppendLine();
            sb.AppendLine("## 概述");
            sb.AppendLine("本系统支持在对话中直接调用工具函数，即使是不支持原生函数调用的AI模型也可以使用。");
            sb.AppendLine("只需在对话中使用函数调用语法，系统会自动识别并执行。");
            sb.AppendLine();
            sb.AppendLine("## 支持的工具");
            sb.AppendLine();

            var tools = GetSupportedTools();

            sb.AppendLine("### 📁 基础项目工具");
            var basicTools = tools.Where(t => new[] { "scan_project_structure", "get_project_overview", "deep_content_search", "analyze_file_relationships" }.Contains(t.Key));
            foreach (var tool in basicTools)
            {
                sb.AppendLine($"• **{tool.Key}**: {tool.Value}");
            }
            sb.AppendLine();

            sb.AppendLine("### 🔍 增强文件访问与代码智能");
            var enhancedTools = tools.Where(t => new[] { "get_path_info", "get_file_content", "smart_file_access", "search_paths", "batch_file_info", "analyze_directory_structure", "code_search", "open_file_range" }.Contains(t.Key));
            foreach (var tool in enhancedTools)
            {
                sb.AppendLine($"• **{tool.Key}**: {tool.Value}");
            }
            sb.AppendLine();

            sb.AppendLine("### 📊 内容分析工具");
            var analysisTools = tools.Where(t => new[] { "get_file_summary", "extract_key_information", "get_content_statistics", "analyze_story" }.Contains(t.Key));
            foreach (var tool in analysisTools)
            {
                sb.AppendLine($"• **{tool.Key}**: {tool.Value}");
            }
            sb.AppendLine();

            sb.AppendLine("## 使用示例");
            sb.AppendLine();
            sb.AppendLine("### 基础操作");
            sb.AppendLine("```");
            sb.AppendLine("请帮我分析项目结构: scan_project_structure()");
            sb.AppendLine("查看项目概览: get_project_overview()");
            sb.AppendLine("搜索关键词'主角': deep_content_search(主角)");
            sb.AppendLine("分析文件关系: analyze_file_relationships()");
            sb.AppendLine("```");
            sb.AppendLine();
            sb.AppendLine("### 代码智能与文件查看");
            sb.AppendLine("```");
            sb.AppendLine("代码搜索: code_search(Logger|*.cs|30)");
            sb.AppendLine("查看文件片段: open_file_range(DocumentCreationSystem/Services/AgentToolService.cs|1|60)");
            sb.AppendLine("获取诊断: get_diagnostics() 或 get_diagnostics(DocumentCreationSystem/DocumentCreationSystem.csproj)");
            sb.AppendLine("找引用: find_references(DocumentCreationSystem/Services/AgentToolService.cs|100|10)");
            sb.AppendLine("重命名预览: rename_symbol_preview(DocumentCreationSystem/Services/AgentToolService.cs|100|10|NewName)");
            sb.AppendLine("```");
            sb.AppendLine();
            sb.AppendLine("## 注意事项");
            sb.AppendLine("- 工具调用会自动执行并返回结果");
            sb.AppendLine("- 支持带参数和不带参数的调用");
            sb.AppendLine("- 如果路径不存在，系统会尝试使用当前项目路径");
            sb.AppendLine("- 工具执行失败时会显示错误信息");

            return sb.ToString();
        }
    }
}
